package com.icode.gulimall.search.sevice.impl;

import com.alibaba.fastjson.JSON;
import com.icode.common.to.es.SkuEsModel;
import com.icode.gulimall.search.config.GulimallElastcSearchConfig;
import com.icode.gulimall.search.constant.EsConstant;
import com.icode.gulimall.search.sevice.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: my_code
 * @Create: 2020-11-30 20:36
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //保存es
        //1.给es建立索引。product，建立好映射关系

        //2.给es中保存这些数据
        //参数 BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String jsonString = JSON.toJSONString(model);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, GulimallElastcSearchConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            log.error("ElasticSearch批量执行失败:{}", e);
        }
        // 成功上架的商品id
        List<String> collect = Arrays.stream(bulk.getItems())
                .map(item -> item.getId())
                .collect(Collectors.toList());
        log.info("商品上架成功：{}", collect);

        // TODO 如果批量错误   有错误返回true
        boolean b = bulk.hasFailures();
        //调整返回值，上架有错误返回false
        return !b;
    }
}
